package ThreadProjectTest.reentrant;

import java.util.concurrent.locks.ReentrantLock;

/*
 * Author: JacksonCoder
 * FileName: BankAccount
 * Version: 1.0.0
 */
public class BankAccount {
    private double balance;
    private final ReentrantLock lock = new ReentrantLock();

    public BankAccount(double initialBalance){
        this.balance = initialBalance;
    }

    public void deposit(double amount){
        lock.lock();
        try{
            System.out.println(Thread.currentThread().getName() + "正在存款：" + amount);
            balance += amount;
            System.out.println(Thread.currentThread().getName() + "存款成功，当前余额：" + balance);
        } finally{
            lock.unlock();
        }
    }

    public void withdraw(double amount){
        lock.lock(); // 获取锁
        try {
            if (balance >= amount) {
                System.out.println(Thread.currentThread().getName() + " 正在取款: " + amount);
                balance -= amount;
                System.out.println(Thread.currentThread().getName() + " 取款完成，当前余额: " + balance);
            } else {
                System.out.println(Thread.currentThread().getName() + " 取款失败，余额不足！");
            }
        } finally {
            lock.unlock(); // 释放锁
        }
    }

    // 查询余额
    public double getBalance() {
        lock.lock(); // 获取锁
        try {
            return balance;
        } finally {
            lock.unlock(); // 释放锁
        }
    }

}
